package com.test.hello.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import com.test.hello.model.User;
import com.test.hello.service.UserService;

@Controller
@RequestMapping(value = "/service")
public class ShiroLogin {
	@Autowired
	private UserService service;
	
	 /**
     * 实际的登录代码
     * 如果登录成功，跳转至首页；登录失败，则将失败信息反馈对用户
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "dologin",method = RequestMethod.POST)
    public String doLogin(@Validated User user,BindingResult bindingResult,RedirectAttributes redirectAttributes,HttpSession httpSession) {
//    	System.out.println(service.selectByPrimaryKey(1L).getUsername());
//        String msg = "";
//        String userName = request.getParameter("userName");
//        String password = request.getParameter("password");
//
//        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
//        token.setRememberMe(true);
//        Subject subject = SecurityUtils.getSubject();
//        try {
//            subject.login(token);
//            if (subject.isAuthenticated()) {
//            	System.out.println("成功");
//                return "index";
//            } else {
//            	System.out.println("失败");
//                return "redirect:/login.jsp";
//            }
//        } catch (IncorrectCredentialsException e) {
//            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
//            httpSession.setAttribute("message", msg);
//            System.out.println(msg);
//        } catch (ExcessiveAttemptsException e) {
//            msg = "登录失败次数过多";
//            httpSession.setAttribute("message", msg);
//            System.out.println(msg);
//        } catch (LockedAccountException e) {
//            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
//            httpSession.setAttribute("message", msg);
//            System.out.println(msg);
//        } catch (DisabledAccountException e) {
//            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
//            httpSession.setAttribute("message", msg);
//            System.out.println(msg);
//        } catch (ExpiredCredentialsException e) {
//            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
//            httpSession.setAttribute("message", msg);
//            System.out.println(msg);
//        } catch (UnknownAccountException e) {
//            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
//            httpSession.setAttribute("message", msg);
//            System.out.println(msg);
//        } catch (UnauthorizedException e) {
//            msg = "您没有得到相应的授权！" + e.getMessage();
//            httpSession.setAttribute("message", msg);
//            
//            System.out.println(msg);
//        }
//        return "redirect:/login.jsp";
    	
    	 try {  
             if(bindingResult.hasErrors()){
            	 redirectAttributes.addFlashAttribute("message11","用户名或密码错误");
                 return "/login.jsp";  
             }  
             //使用权限工具进行用户登录，登录成功后跳到shiro配置的successUrl中，与下面的return没什么关系！  
             SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));  
             return "user/user";  
         } catch (AuthenticationException e) {  
             redirectAttributes.addFlashAttribute("message11","用户名或密码错误");
             return "redirect:/login.jsp";  
         }  
    	
    }
    
    @RequestMapping(value="/logout",method=RequestMethod.GET)    
    public String logout(RedirectAttributes redirectAttributes ){   
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息  
        SecurityUtils.getSubject().logout();    
        redirectAttributes.addFlashAttribute("message11", "您已安全退出");    
        return "redirect:/login";  
    }
    
    @RequestMapping("/403")  
    public String unauthorizedRole(){  
        return "/403";  
    }  
}
